﻿using System;
using System.IO;

namespace socket_client
{
    using System.Collections.Concurrent;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    public static class AsyncFileLogger
    {
        private static readonly string LogFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SaveData");
        private static readonly BlockingCollection<string> LogQueue = new BlockingCollection<string>();
        private static readonly Task LoggingTask;
        public static TextBox _logTextBox;
        static AsyncFileLogger()
        {
            // 创建日志目录
            if (!Directory.Exists(LogFolder))
            {
                Directory.CreateDirectory(LogFolder);
            }

            // 启动后台写入任务
            LoggingTask = Task.Factory.StartNew(ProcessLogs, TaskCreationOptions.LongRunning);
        }
        // 初始化时绑定文本框控件
        public static void Initialize(TextBox textBox)
        {
            _logTextBox = textBox;
        }

        public static void WriteLog(string message)
        {
            string logEntry = $"[{DateTime.Now:yyyy/MM/dd/HH:mm}] {message}{Environment.NewLine}";
            LogQueue.Add(logEntry);


            if (_logTextBox == null) return; // 新增空引用检查
            if (_logTextBox.InvokeRequired)
            {
                _logTextBox.BeginInvoke(new Action<string>(WriteLog), message);
                return;
            }
            // 确保每次写入的内容都自动换行
            _logTextBox.AppendText(logEntry);

            _logTextBox.ScrollToCaret();
        }

        private static void ProcessLogs()
        {
            foreach (var logEntry in LogQueue.GetConsumingEnumerable())
            {
                string logFile = Path.Combine(LogFolder, $"Log_{DateTime.Now:yyyyMMdd}.log");
                File.AppendAllText(logFile, logEntry + Environment.NewLine);
            }
        }

        // 应用退出时调用
        public static void Shutdown()
        {
            LogQueue.CompleteAdding();
            LoggingTask.Wait();
        }
    }
}
